'''
与arduino建立通讯
'''
import time
import serial
import serial.tools.list_ports
import numpy as np
import configparser
import threading

from HCJ_DB_Helper import HCJ_database

card_id_list=["1671116496","18220717443"]
class SerialArduino():
    def __init__(self,Baudrate=9600):
        cf = configparser.ConfigParser()
        cf.read("./config.ini")
        Port = cf.get("Setting", "Port")
        self.port=Port
        self.Baudrate=Baudrate
        self.con = self.ConnectArduino()
        self.is_door_able_run=True
    def GetAllPort(self):
        port_list = []
        for port in list(serial.tools.list_ports.comports()):
            port_list.append(port[0])
        return port_list
    def IsPortExit(self):
        port_list = self.GetAllPort()
        if self.port in port_list:
            return True
        else:
            return False
    def ConnectArduino(self):
        Flag=False
        if self.IsPortExit():
            try:
                ser = serial.Serial(self.port,self.Baudrate, timeout=1)
                Flag = True
            except:
                Flag=False
        else:
            Flag=False
        if Flag:
            return ser
        else:
            print("未能成功链接Arduino端口，请检查1端口是否存在，2端口是否被占用")
            return Flag
    def SendByteToArduino(self,str1):
        con = self.ConnectArduino()
        SendFlag=False
        RecvFlag=False
        if con:
            s="<%s>\n"%str1
            con.write(s.encode('utf-8'))
            SendFlag = True
            time.sleep(0.5)
            str = con.read_all()
            str1 = str.decode("utf-8")
            print(str1)
            if "ok" in str1:
                RecvFlag=True
                print("发送成功")
            print(str1)
            if not RecvFlag:
                print("发送成功，但未接收到反馈信息，请检查Arduino板Mode")
        return SendFlag

    def SendToArduino(self,code):
        if self.con:
            s="<%s>\n"%code
            self.con.write(s.encode('utf-8'))
    def ListenArduino(self):
        print("门禁服务开启")
        SendFlag = False
        RecvFlag = False
        while self.con:
            str = self.con.read_until('%')
            if len(phoneOrderList)>0 and self.is_door_able_run:
                # 当获得到手机指令且当门可以开的时候
                self.opendoor(phoneOrderList[0][1],phoneOrderList[0][2])
                sql = "UPDATE `person_info` SET `phone_code`='0' where `id`=%s" % phoneOrderList[0][0]
                db.upda_sql(sql)
                del phoneOrderList[0]

            if len(str)>0:
                str1 = str.decode("utf-8")
                print(str1)
                if '(' in str1:
                    str1=str1.split(')')[0]
                    str1=str1.split('(')[1]
                    if "close" in str1:
                        self.is_door_able_run = True
                    print(str1)
                    # 都是指令
                    if '@' in str1:
                        card_id=str1[:-1]
                        is_checkin=checkCardID(card_id)
                        if is_checkin:
                            self.opendoor(is_checkin[0], is_checkin[1])
    def opendoor(self,name,card):
        print("接受到姓名：%s 卡号：%s，发送开门指令" % (name,card))
        self.SendToArduino(1)
        self.is_door_able_run = False
def thread_input(n):
    global code
    while 1:
        code=int(input("请输入:"))
def getAllCardId():
    sql = "SELECT `name`,`card_id` FROM `person_info` WHERE 1"
    print(sql)
    t = db.do_sql(sql)
    print(t)
def checkCardID(card_id):
    sql = "SELECT `name`,`card_id` FROM `person_info` WHERE `card_id`='%s'"%card_id
    t = db.do_sql_one(sql)
    if t!=None:
        return t
    else:
        return False
def listenPhone(n):
    global phoneOrderList
    while 1:
        sql = "SELECT `id`,`name`,`card_id`,`phone_code` FROM `person_info` WHERE `phone_code`='1'"
        t = db.do_sql_one(sql)
        if t!=None:
            t=list(t)
            if t not in phoneOrderList:
                phoneOrderList.append(t)
            sql="UPDATE `person_info` SET `phone_code`='5' where `id`=%s"%t[0]
            print(sql)
            print(phoneOrderList)
            db.upda_sql(sql)
        time.sleep(1)
phoneOrderList=[]
db = HCJ_database()
if __name__ == '__main__':
    # getAllCardId()

    t1 = threading.Thread(target=thread_input, args=("t1",))
    t1.start()
    t2 = threading.Thread(target=listenPhone, args=("t2",))
    t2.start()
    ser = SerialArduino()
    ser.ListenArduino()

